package com.meepo.usercenter.profile

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.google.android.material.appbar.CollapsingToolbarLayout
import com.jaeger.library.StatusBarUtil
import com.meepo.basic.router.RouterManager
import com.meepo.basic.components.ImagePopup
import com.meepo.basic.components.listfragment.ListFragmentParams
import com.meepo.framework.design.viewpager.adapter.DefaultFragmentStatePagerAdapter
import com.meepo.basic.schema.user.User
import com.meepo.basic.components.view.MeepoActivity
import com.meepo.framework.design.button.SlickButton
import com.meepo.framework.design.helper.ColorHelper
import com.meepo.framework.design.helper.ImageLoader
import com.meepo.framework.design.helper.StatusBarHelper
import com.meepo.framework.design.tabs.ViewPagerHelper
import com.meepo.framework.design.tabs.buildins.commonnavigator.CommonNavigator
import com.meepo.framework.design.tabs.sample.TextTab
import com.meepo.framework.design.tabs.sample.navadapters.ColorTransitionNavigatorAdapter
import com.meepo.usercenter.API
import com.meepo.usercenter.R
import com.xiaojinzi.component.anno.RouterAnno
import com.xiaojinzi.component.support.ParameterSupport
import kotlinx.android.synthetic.main.user_profile_activtiy.*
import kotlin.math.abs

@RouterAnno(hostAndPath = RouterManager.UserModule.UserProfile_Path)
class UserProfileActivity : MeepoActivity() {

    private lateinit var mUserId: String

//    private val mTabEntities = listOf(
//        DefaultTab("帖子", 0, 0),
//        DefaultTab("评论", 0, 0),
//        DefaultTab("话题", 0, 0)
//    )
//    private var lastState = 1

    @SuppressLint("SetTextI18n")
    private fun applyUserInfo(user: User?) {
        if (user == null) finish()
        user?.let {
            // 顶部头像
            ImageLoader.loadImage(this, user.avatar, title_avatar)
            // 顶部昵称
            title_nickname_tv.text = user.nickname ?: ""

            // 封面
//            ImageLoader.loadImageBackground(this, user.getCover(), collapsing_tool_bar)
            ImageLoader.loadImage(this, user.getCover(), cover_iv)

            // 头像
            ImageLoader.loadImage(this, user.avatar, uc_avater)
            uc_avater.setOnClickListener { ImagePopup.popup(this, uc_avater, user.avatar) }

            // 昵称
            nickname_tv.text = user.nickname ?: ""

            // 按钮
            if (user.isMe()) {
                extra_btn.text = "编辑资料"
                extra_btn.setOnClickListener { RouterManager.UserModule.routeToUserInfoEdit(this) }
                extra_btn.color = ColorHelper.parseColor("#33000000")
                extra_btn.setTextColor(Color.WHITE)
            } else {

                if (user.followed) {
                    extra_btn.type = SlickButton.BUTTON_TYPE_DEFAULT
                    extra_btn.color = this.resources.getColor(R.color.sub_text_color)
                    extra_btn.text = "已关注"
                } else {
                    extra_btn.type = SlickButton.BUTTON_TYPE_PRIMARY
                    extra_btn.color = this.resources.getColor(R.color.primary_color)
                    extra_btn.text = "关注"
                    extra_btn.setTextColor(Color.WHITE)
                }

                extra_btn.setOnClickListener {

                    if (user.followed) {
                        presenter.call(
                            API.instance().deleteRelation(User.RELATION_TYPE_FOLLOW, mUserId),
                            { applyUserInfo(user.setUnfollowed()) }
                        )
                    } else {
                        presenter.call(
                            API.instance().addRelation(User.RELATION_TYPE_FOLLOW, mUserId),
                            { applyUserInfo(user.setFollowed()) }
                        )
                    }
                }
            }

            // 用户签名
            sign_tv.text = user.sign ?: ""

            // 统计
            like_count_tv.text = "" + (user.stat?.likedCount ?: 0)
            follow_count_tv.text = "" + (user.stat?.followingCount ?: 0)
            follower_count_tv.text = "" + (user.stat?.followerCount ?: 0)
        }
    }

    override fun initData() {
        presenter.call(
            API.instance().getUserInfo(mUserId),
            { rsp -> applyUserInfo(rsp.data) },
            { finish() }
        )
    }


    override fun initView(view: View, savedInstanceState: Bundle?) {
        mUserId = ParameterSupport.getString(intent, "userId", null)!!

        back_iv.setOnClickListener { finish() }

        initListener()
        initTab()
//        initStatus()
    }

    private fun initTab() {
        val fragments = listOf(
            RouterManager.FeedModule.routeToFeedList(
                authorId = mUserId,
                listFragmentParams = ListFragmentParams(enablePullRefresh = false)
            ),
            RouterManager.FeedModule.routeToCommentList(
                authorId = mUserId,
                listFragmentParams = ListFragmentParams(enablePullRefresh = false)
            ),

            RouterManager.FeedModule.routeToTopicList(
                authorId = mUserId,
                simple = true,
                listFragmentParams = ListFragmentParams(enablePullRefresh = false)
            )
        )

        val tabs = listOf("帖子", "评论", "话题").map {
            TextTab(
                it, it,
                selectedTextColor = resources.getColor(com.meepo.feed.R.color.primary_color),
                unSelectedTextColor = resources.getColor(com.meepo.feed.R.color.primary_text_color)
            )
        }.toList()

        magic_indicator.navigator = CommonNavigator(
            this,
            ColorTransitionNavigatorAdapter(tabs) { index -> view_pager.currentItem = index }, true
        )

        view_pager.adapter = DefaultFragmentStatePagerAdapter(supportFragmentManager, fragments)

        ViewPagerHelper.bind(magic_indicator, view_pager)

        view_pager.currentItem = 0

//
//        uc_tablayout.setTabData(mTabEntities)
//        uc_viewpager.adapter =
//            DefaultFragmentStatePagerAdapter(
//                supportFragmentManager,
//                fragments
//            )
//
//        // todo tab
//        uc_tablayout.setOnTabSelectListener(object : OnTabSelectListener {
//            override fun onTabSelect(position: Int) {
//                uc_viewpager.currentItem = position
//            }
//
//            override fun onTabReselect(position: Int) {}
//        })
//        uc_viewpager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
//            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
//            override fun onPageSelected(position: Int) {
//                uc_tablayout.currentTab = position
//            }
//
//            override fun onPageScrollStateChanged(state: Int) {}
//        })
    }

    /**
     * 绑定事件
     */
    private fun initListener() {
        appbar_layout.addOnOffsetChangedListener(OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val percent = abs(verticalOffset).toFloat() / appBarLayout.totalScrollRange.toFloat()

            if (title_center_layout != null && uc_avater != null) {
                title_center_layout.alpha = percent

//                StatusBarUtil.setTranslucentForImageView(this, (255f * percent).toInt(), null)
                when (percent) {
                    0f -> {
                        groupChange(1f, 1)
                    }
                    1f -> {
                        uc_avater.visibility = View.GONE
                        groupChange(1f, 2)
                    }
                    else -> {
                        uc_avater.visibility = View.VISIBLE
                        groupChange(percent, 0)
                    }
                }
            }
        })
    }

    /**
     * 初始化状态栏位置
     */
    private fun initStatus() {
        //4.4以下不支持状态栏变色
        //注意了，这里使用了第三方库 StatusBarUtil，目的是改变状态栏的alpha
        StatusBarUtil.setTransparentForImageView(this@UserProfileActivity, null)
        //这里是重设我们的title布局的topMargin，StatusBarUtil提供了重设的方法，但是我们这里有两个布局
        //TODO 关于为什么不把Toolbar和@layout/layout_uc_head_title放到一起，是因为需要Toolbar来占位，防止AppBarLayout折叠时将title顶出视野范围
        val statusBarHeight = StatusBarHelper.getHeight(this@UserProfileActivity)
        val lp1 = title_layout!!.layoutParams as CollapsingToolbarLayout.LayoutParams
        lp1.topMargin = statusBarHeight
        title_layout!!.layoutParams = lp1
        val lp2 = toolbar!!.layoutParams as CollapsingToolbarLayout.LayoutParams
        lp2.topMargin = statusBarHeight
        toolbar!!.layoutParams = lp2
    }

    /**
     * @param alpha
     * @param state 0-正在变化 1展开 2 关闭
     */
    private fun groupChange(alpha: Float, state: Int) {
//        lastState = state
//        uc_setting_iv.alpha = alpha
        when (state) {
            1 ->
                view_pager!!.setNoScroll(true)
            2 ->
                view_pager!!.setNoScroll(true)
            0 -> {
                //为什么禁止滑动？在介于开关状态之间，不允许滑动，开启可能会导致不好的体验
                view_pager!!.setNoScroll(true)
            }
        }
    }

    override fun setUpContentLayout(): Int = R.layout.user_profile_activtiy
}